package org.lim.application.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.lim.application.service.UserApplicationService;
import org.lim.domain.space.service.SpaceDomainService;
import org.lim.domain.space.service.SpaceUserDomainService;
import org.lim.infrastructure.exception.BusinessException;
import org.lim.infrastructure.exception.ErrorCode;
import org.lim.infrastructure.exception.ThrowUtils;
import org.lim.interfaces.dto.space.SpaceAddRequest;
import org.lim.interfaces.dto.space.SpaceQueryRequest;
import org.lim.domain.space.entity.Space;
import org.lim.domain.space.entity.SpaceUser;
import org.lim.domain.user.entity.User;
import org.lim.domain.space.valueobject.SpaceLevelEnum;
import org.lim.domain.space.valueobject.SpaceRoleEnum;
import org.lim.domain.space.valueobject.SpaceTypeEnum;
import org.lim.interfaces.vo.space.SpaceVO;
import org.lim.interfaces.vo.user.UserVO;
import org.lim.application.service.SpaceApplicationService;
import org.lim.infrastructure.mapper.SpaceMapper;
import org.lim.application.service.SpaceUserApplicationService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author sk
 * @description 针对表【space(空间)】的数据库操作Service实现
 * @createDate 2025-05-29 10:25:12
 */
@Service
public class SpaceApplicationServiceImpl extends ServiceImpl<SpaceMapper, Space>
        implements SpaceApplicationService {
    @Resource
    UserApplicationService userApplicationService;
    @Resource
    private TransactionTemplate  transactionTemplate;
    @Resource
    private SpaceUserApplicationService spaceUserApplicationService;
    @Resource
    private SpaceDomainService spaceDomainService;
    Map<Long, Object> lockMap = new ConcurrentHashMap<>();
//    @Resource
//    @Lazy
//    private DynamicShardingManager dynamicShardingManager;



    /**
     *校验空间级别名称是否有效
     */

    @Override
    public void validSpace(Space space, boolean isAdd) {
       spaceDomainService.validSpace(space, isAdd);
    }
    /**
     * 更具空间级别填充限额
     */

    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        //根据空间级别，自动填充限额
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (spaceLevelEnum != null) {
            long maxSize = spaceLevelEnum.getMaxSize();
            if (space.getMaxSize() == null) {
                space.setMaxSize(maxSize);
            }
            long maxCount = spaceLevelEnum.getMaxCount();
            if (space.getMaxCount() == null) {
                space.setMaxCount(maxCount);
            }
        }
    }
    /**
     * 获取spaceVO对象
     */

    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        Long userId = space.getUserId();
        if (userId != null) {
            User user = userApplicationService.getUserById(userId);
            UserVO userVO = userApplicationService.getUserVO(user);
            spaceVO.setUser(userVO);
        }
        return spaceVO;
    }

    /**
     * 分页查询
     */
    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        //  对象列表 => 封装对象列表
        List<SpaceVO> spaceVOList = spaceList.stream().map(SpaceVO::objToVo)
                .toList();
        //  1. 关联查询用户信息
        Set<Long> userIdSet = spaceList.stream()
                .map(Space::getUserId)
                .collect(Collectors.toSet());
        Map<Long, List<User>> userIdListMap = userApplicationService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        //  2. 填充信息
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userIdListMap.containsKey(userId)) {
                user = userIdListMap.get(userId).get(0);
            }
            spaceVO.setUser(userApplicationService.getUserVO(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;

    }
    /**
     * 封装分页查询参数
     */
    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
       QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
       if (spaceQueryRequest == null) {
           return queryWrapper;
       }
       // 从对象中取值
        Long id = spaceQueryRequest.getId();
        Long userId = spaceQueryRequest.getUserId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Integer spaceType = spaceQueryRequest.getSpaceType();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();


        // 创建查询条件
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(ObjUtil.isNotEmpty(spaceName), "spaceName", spaceName);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel), "spaceLevel", spaceLevel);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceType), "spaceType", spaceType);

        //排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);

        return queryWrapper;
    }

    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser){
        // 将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest, space);
        // 默认值
        if(StrUtil.isBlank(spaceAddRequest.getSpaceName())){
            space.setSpaceName("默认空间");
        }
        if(spaceAddRequest.getSpaceLevel() == null){
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if(space.getSpaceType() == null){
            space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        //填充容量和大小
        this.fillSpaceBySpaceLevel(space);
        //校验参数
        this.validSpace(space,true);
        // 校验权限，非管理员只能创建普通空间
        Long userId = loginUser.getId();
        space.setUserId(userId);
        if(SpaceLevelEnum.COMMON.getValue() != space.getSpaceLevel() && !loginUser.isAdmin()){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有权限创建指定级别的空间");
        }
        // 控制同一个用户只能创建一个私有空间以及一个团队空间,通过锁加事物控制
//
        Object lock = lockMap.computeIfAbsent(userId, k -> new Object());
        synchronized (lock) {
            Long newSpaceId;
            try {
                newSpaceId = transactionTemplate.execute(status -> {
                    // 判断是否已有空间
                    boolean exists = this.lambdaQuery()
                            .eq(Space::getUserId, userId)
                            .eq(Space::getSpaceType, space.getSpaceType())
                            .exists();
                    //如果已有空间，就不能再创建
                    ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "已有该空间，不能再创建");

                    //创建空间
                    boolean result = this.save(space);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建空间失败");
                    // 如果是团队空间，关联新增团队成员记录
                    if (SpaceTypeEnum.TEAM.getValue() == spaceAddRequest.getSpaceType()) {
                        SpaceUser spaceUser = new SpaceUser();
                        spaceUser.setSpaceId(space.getId());
                        spaceUser.setUserId(userId);
                        spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                        result = spaceUserApplicationService.save(spaceUser);
                        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建团队成员记录失败");
                    }
//                        // 创建分表
//                    dynamicShardingManager.createSpacePictureTable(space);
                        // 返回新写入的数据 id
                    return space.getId();

                });
            } finally {
                // 防止内存泄露
                lockMap.remove(userId);
            }
            return Optional.ofNullable(newSpaceId).orElse(-1L);
        }

    }

    /**
     * 校验空间权限
     * @param loginUser 登录用户
     * @param space 空间
     */
    @Override
    public void checkSpaceAuth(User loginUser, Space space) {
        //仅本人或管理员可编辑
        if (!space.getUserId().equals(loginUser.getId()) && !loginUser.isAdmin()) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }

}




